//
//  main.swift
//  photoinfo
//
//  Created by SunBooShi on 2021/6/2.
//

import Foundation

struct PhotoInfo {
    // 品牌
    var make: String?
    // 型号
    var model: String?
    // 镜头
    var lensModel: String?
    // 光圈
    var fNumber: Double?
    // 曝光
    var exposureTime: Double?
    // ISO
    var ISOSpeedRating: Int?
    // 焦距
    var focalLength: Double?
    // 换算到35mm的焦距
    var focalLenIn35mmFilm: Double?
    // 日期
    var dateTime: String?
    var desc: String {
        return """
            品牌: \(make ?? "")
            相机: \(model ?? "")
            镜头: \(lensModel ?? "")
            光圈: \(fNumber ?? 0.0)
            快门: \(exposureTime ?? 0.0)
            ISO: \(ISOSpeedRating ?? 0)
            焦距: \(focalLength ?? 0.0)
            焦距(35): \(focalLenIn35mmFilm ?? 0.0)
            日期: \(dateTime ?? "")
            """
    }
}

func getPhotoInfo(file:String) -> PhotoInfo? {
    let url = NSURL(fileURLWithPath: file)
    guard let source = CGImageSourceCreateWithURL(url, nil) else { return nil }
    let dict = CGImageSourceCopyPropertiesAtIndex(source, 0, nil)
    var info = PhotoInfo()
    if let metadata = dict as? [String: AnyObject] {
        if let tiff = metadata["{TIFF}"] as? [String: AnyObject] {
            let make = tiff["Make"] as? String
            info.make = make ?? ""
            let model = tiff["Model"] as? String
            info.model = model ?? ""
        }
        if let exif = metadata["{Exif}"] as? [String: AnyObject] {
            let LensModel = exif["LensModel"] as? String
            info.lensModel =  LensModel ?? ""
            let FNumber = exif["FNumber"] as? Double
            info.fNumber = FNumber ?? 0.0
            let ExposureTime = exif["ExposureTime"] as? Double
            info.exposureTime = ExposureTime ?? 0.0
            if let ISOSpeedRatings = exif["ISOSpeedRatings"] as? [Int] {
                if ISOSpeedRatings.count > 0 {
                    info.ISOSpeedRating = ISOSpeedRatings[0]
                }
                else {
                    info.ISOSpeedRating = 0
                }
            }
            else {
                info.ISOSpeedRating = 0
            }
            let FocalLength = exif["FocalLength"] as? Double
            info.focalLength = FocalLength ?? 0.0
            let FocalLenIn35mmFilm = exif["FocalLenIn35mmFilm"] as? Double
            info.focalLenIn35mmFilm = FocalLenIn35mmFilm ?? 0.0
            let DateTimeOriginal = exif["DateTimeOriginal"] as? String
            info.dateTime = DateTimeOriginal ?? ""
        }
    }
    return info
}

if CommandLine.argc == 2 {
    let info = getPhotoInfo(file: CommandLine.arguments[1])
    print(info?.desc ?? "")
}
else {
    print("Usage: photoinfo /photo/path")
}
